package ins.framework.kafka;

import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;

public class ESoperation {
    public static Client getClient(String clusterName,String ...hosts){
        Settings settings = Settings.builder()
                .put("cluster.name", clusterName).build();
        try {
            TransportClient client = new PreBuiltTransportClient(settings);
            for(int i=0;i<hosts.length;i++){
                client.addTransportAddress(new TransportAddress(InetAddress.getByName(hosts[i]), 9300));
            }
            return client;
        }catch (Exception e){
            return null;
        }
    }
    public static DeleteResponse delete(Client client, String index, String type, String id){
        return client.prepareDelete(index,type,id).get();
    }
    public static UpdateResponse updateAndCreate(Client client, String index, String type, String id, String value){
        //更新时传的也是全量数据

        //https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-docs-update.html#java-docs-update-api-upsert
/*        IndexRequest indexRequest = new IndexRequest(index,type,id);
        indexRequest.source(value, XContentType.JSON);*/

        //doc merge
        UpdateRequest updateRequest = new UpdateRequest(index,type,id)
                .doc(value,XContentType.JSON)
                .upsert(value,XContentType.JSON);
        try{
            return client.update(updateRequest).get();
        }catch (Exception e){
            return null;
        }
    }
}
